package resource

import (
	"operator/pkg/types/mesh"
	"strconv"
	"strings"
)

type PodResource struct {
	Resource []*mesh.Resource `json:"resource"`
	IP       string           `json:"ip"`
}

func (r *PodResource) ToMap(uid string) map[ResourceString][]Resource {
	m := make(map[ResourceString][]Resource)
	for _, i := range r.Resource {
		rs := GenerateResourceString(*i.Version, *i.Path)
		if _, ok := m[rs]; ok {
			m[rs] = append(m[rs], Resource{
				Protocol: *i.Protocol,
				Host:     r.IP + ":" + strconv.Itoa(int(*i.Port)),
				NetWork:  *i.NetWork,
				TimeOut:  *i.Timeout,
				Uid:      uid,
			})
		} else {
			m[rs] = []Resource{
				{
					Protocol: *i.Protocol,
					Host:     r.IP + ":" + strconv.Itoa(int(*i.Port)),
					NetWork:  *i.NetWork,
					TimeOut:  *i.Timeout,
					Uid:      uid,
				},
			}
		}
	}

	return m
}

type ResourceString string

func (rs ResourceString) Version() string {
	arr := strings.SplitN(string(rs), "&", 2)
	return arr[0]
}

func (rs ResourceString) Path() string {
	arr := strings.SplitN(string(rs), "&", 2)
	return arr[1]
}

func GenerateResourceString(version, path string) ResourceString {
	return ResourceString(version + "&" + path)
}

type Resource struct {
	Protocol string `json:"protocol"` //数据的类型
	Host     string `json:"host"`     //ip+port  127.0.0.1:111
	NetWork  string `json:"network"`  //tcp http udp
	TimeOut  int32  `json:"timeout"`
	Uid      string `json:"-"`
}
